
package com.joolun.cloud.weixin.admin.controller;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.joolun.cloud.common.core.util.R;
import com.joolun.cloud.common.log.annotation.SysLog;
import com.joolun.cloud.common.security.annotation.Inside;
import com.joolun.cloud.weixin.admin.config.mp.WxMpConfiguration;
import com.joolun.cloud.weixin.admin.service.WxUserService;
import com.joolun.cloud.weixin.common.constant.ConfigConstant;
import com.joolun.cloud.weixin.common.dto.WxTemplateMsgSendDTO;
import com.joolun.cloud.weixin.common.entity.WxTemplateMsg;
import com.joolun.cloud.weixin.admin.service.WxTemplateMsgService;
import com.joolun.cloud.weixin.common.entity.WxUser;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.mp.api.WxMpTemplateMsgService;
import me.chanjar.weixin.mp.bean.template.WxMpTemplateMessage;
import org.springframework.web.bind.annotation.*;
import org.springframework.security.access.prepost.PreAuthorize;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import java.util.List;
import java.util.concurrent.atomic.AtomicReference;

/**
 * 微信模板/订阅消息
 *
 * @author www.joolun.com
 * @date 2020-04-16 17:30:03
 */
@Slf4j
@RestController
@AllArgsConstructor
@RequestMapping("/wxtemplatemsg")
@Api(value = "wxtemplatemsg", tags = "微信模板/订阅消息管理")
public class WxTemplateMsgController {

    private final WxTemplateMsgService wxTemplateMsgService;
	private final WxUserService wxUserService;

    /**
     * 分页列表
     * @param page 分页对象
     * @param wxTemplateMsg 微信模板/订阅消息
     * @return
     */
    @ApiOperation(value = "分页列表")
    @GetMapping("/page")
    @PreAuthorize("@ato.hasAuthority('wxma:wxtemplatemsg:index','wxmp:wxtemplatemsg:index')")
    public R getPage(Page page, WxTemplateMsg wxTemplateMsg) {
        return R.ok(wxTemplateMsgService.page(page, Wrappers.query(wxTemplateMsg)));
    }

    /**
     * 微信模板/订阅消息查询
     * @param id
     * @return R
     */
    @ApiOperation(value = "微信模板/订阅消息查询")
    @GetMapping("/{id}")
    @PreAuthorize("@ato.hasAuthority('wxma:wxtemplatemsg:get','wxmp:wxtemplatemsg:get')")
    public R getById(@PathVariable("id") String id) {
        return R.ok(wxTemplateMsgService.getById(id));
    }

    /**
     * 微信模板/订阅消息新增
     * @param wxTemplateMsg 微信模板/订阅消息
     * @return R
     */
    @ApiOperation(value = "微信模板/订阅消息新增")
    @SysLog("新增微信模板/订阅消息")
    @PostMapping
    @PreAuthorize("@ato.hasAuthority('wxma:wxtemplatemsg:add','wxmp:wxtemplatemsg:add')")
    public R save(@RequestBody WxTemplateMsg wxTemplateMsg) {
		List<WxTemplateMsg> listWxTemplateMsg = wxTemplateMsgService.list(Wrappers.<WxTemplateMsg>lambdaQuery()
				.eq(WxTemplateMsg::getAppId,wxTemplateMsg.getAppId())
				.eq(WxTemplateMsg::getUseType,wxTemplateMsg.getUseType()));
		if(listWxTemplateMsg.size() > 0){
			return R.failed("该用途已有相应模板，请勿重复添加");
		}
        return R.ok(wxTemplateMsgService.save(wxTemplateMsg));
    }

    /**
     * 微信模板/订阅消息修改
     * @param wxTemplateMsg 微信模板/订阅消息
     * @return R
     */
    @ApiOperation(value = "微信模板/订阅消息修改")
    @SysLog("修改微信模板/订阅消息")
    @PutMapping
    @PreAuthorize("@ato.hasAuthority('wxma:wxtemplatemsg:edit','wxmp:wxtemplatemsg:edit')")
    public R updateById(@RequestBody WxTemplateMsg wxTemplateMsg) {
		List<WxTemplateMsg> listWxTemplateMsg = wxTemplateMsgService.list(Wrappers.<WxTemplateMsg>lambdaQuery()
				.eq(WxTemplateMsg::getAppId,wxTemplateMsg.getAppId())
				.eq(WxTemplateMsg::getUseType,wxTemplateMsg.getUseType()));
		if(listWxTemplateMsg.size() == 1){
			if(!listWxTemplateMsg.get(0).getId().equals(wxTemplateMsg.getId())){
				return R.failed("该用途已有相应模板，请勿重复添加");
			}
		}
        return R.ok(wxTemplateMsgService.updateById(wxTemplateMsg));
    }

    /**
     * 微信模板/订阅消息删除
     * @param id
     * @return R
     */
    @ApiOperation(value = "微信模板/订阅消息删除")
    @SysLog("删除微信模板/订阅消息")
    @DeleteMapping("/{id}")
    @PreAuthorize("@ato.hasAuthority('wxma:wxtemplatemsg:del','wxmp:wxtemplatemsg:del')")
    public R removeById(@PathVariable String id) {
        return R.ok(wxTemplateMsgService.removeById(id));
    }

	/**
	 * list列表，可指定useType
	 * @param wxTemplateMsg 微信模板/订阅消息
	 * @return
	 */
	@Inside
	@ApiOperation(value = "list列表")
	@PostMapping("/inside/list")
	public R getList(@RequestBody WxTemplateMsg wxTemplateMsg) {
		return R.ok(wxTemplateMsgService.list(Wrappers.query(wxTemplateMsg).lambda()
				.in(WxTemplateMsg::getUseType,wxTemplateMsg.getUseTypeList())));
	}

	/**
	 * 发送微信小程序订阅消息（服务间调用）
	 * @param
	 * @return
	 */
	@Inside
	@ApiOperation(value = "发送微信小程序订阅消息（服务间调用）")
	@PostMapping("/inside/send/ma")
	public R sendTemplateMsgMaInside(@RequestBody WxTemplateMsgSendDTO wxTemplateMsgSendDTO) {
		//查询出小程序用户信息，并发送订阅消息
		List<WxUser> listWxUser = wxUserService.list(Wrappers.<WxUser>lambdaQuery()
				.eq(WxUser::getMallUserId,wxTemplateMsgSendDTO.getMallUserId())
				.eq(WxUser::getAppType, ConfigConstant.WX_APP_TYPE_1));
		if(listWxUser != null && listWxUser.size() > 0){
			listWxUser.forEach(wxUser -> {
				wxTemplateMsgService.sendWxMaTemplateMsg(wxTemplateMsgSendDTO, wxUser);
			});
		}
		return R.ok();
	}

	/**
	 * 发送微信公众号模板消息（服务间调用）
	 * @param
	 * @return
	 */
	@Inside
	@ApiOperation(value = "发送微信公众号模板消息（服务间调用）")
	@PostMapping("/inside/send/mp")
	public R sendTemplateMsgMpInside(@RequestBody WxTemplateMsgSendDTO wxTemplateMsgSendDTO) {
		//查询出公众号用户信息，并发送模板消息
		List<WxUser> listWxUser2 = wxUserService.list(Wrappers.<WxUser>lambdaQuery()
				.eq(WxUser::getMallUserId,wxTemplateMsgSendDTO.getMallUserId())
				.eq(WxUser::getAppType, ConfigConstant.WX_APP_TYPE_2));
		if(listWxUser2 != null && listWxUser2.size() > 0){
			listWxUser2.forEach(wxUser -> {
				wxTemplateMsgService.sendWxMpTemplateMsg(wxTemplateMsgSendDTO, wxUser);
			});
		}
		return R.ok();
	}

	/**
	 * 发送微信公众号模板消息
	 * @param
	 * @return
	 */
	@ApiOperation(value = "发送微信公众号模板消息")
	@PreAuthorize("@ato.hasAuthority('wxmp:wxtemplatemsg:send')")
	@PostMapping("/send/mp/{appId}")
	public R sendTemplateMsgMp(@RequestBody WxMpTemplateMessage subscribeMessage, @PathVariable("appId") String appId) {
		WxMpTemplateMsgService wxMpTemplateMsgService = WxMpConfiguration.getMpService(appId).getTemplateMsgService();
		List<String> users = StrUtil.split(subscribeMessage.getToUser(),",");
		String error = "";
		for(int i = 0; i<users.size(); i++){
			subscribeMessage.setToUser(users.get(i));
			try {
				wxMpTemplateMsgService.sendTemplateMsg(subscribeMessage);
			} catch (WxErrorException e) {
				error = error + "OpenId：" + users.get(i) + "（"+ e.getError().getErrorMsg() + "）；";
			}
		}
		String e = "";
		if(error != ""){
			e = "；有以下用户发送失败，："+error;
		}
		return R.ok("发送完成" + e);
	}
}
